<template>
  <div>
    <!-- 添加商品弹窗 -->
    <el-dialog title="" :visible.sync="dialogFormVisible" :close-on-press-escape="true" width="60%">
      <div class="goods-layer pad-l-20 pad-r-20 pad-b-20">
        <h3>商品选择</h3>
        <div class="pad-t-30 pad-b-20">
          <el-row>
            <el-col :span="8" class="pad-r-10">
              <el-input @keyup.enter.native="handleSearch" v-model="keyword" class="width-per-100"
                placeholder="请输入商品名称"></el-input>
            </el-col>
            <el-col :span="5" class="pad-r-10">
              <el-cascader v-model="categoryIds" :props="{ checkStrictly: true }" change-on-select placeholder="选择商品分类"
                :options="categoryData" class="default-input" filterable></el-cascader>
            </el-col>
            <el-col :span="5" class="pad-r-10">
              <el-select v-model="goodsTagId" placeholder="商品标签">                
                <el-option v-for="(item, index) in goodsTagList" :key="item.goodsTagId" :label="item.goodsTagName" :value="item.goodsTagId">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="2">
              <el-button type="primary" @click="handleSearch">查询</el-button>
            </el-col>
            <el-col :span="2">
              <el-button @click="cleanSearch">重置</el-button>
            </el-col>
          </el-row>
        </div>
        <!-- 内容列表 -->
        <div class="table-container">
          <el-table ref="multipleTable" :data="dataList" v-loading="listLoading" element-loading-text="加载中"
            style="width: 100%">
            <el-table-column label="商品" prop="title">
              <template slot-scope="scope">
                <div class="flex v-align-c cursor-p">
                  <label><img :src="scope.row.imageUrl" class="picture-avatar"></label>
                  <div class="font-14 pad-l-10">
                    <div><span style="color: red;"
                        v-if="scope.row.errorMsg !== null && scope.row.errorMsg !== undefined">（{{scope.row.errorMsg}}）</span>{{scope.row.title}}
                    </div>
                    <template v-if="scope.row.categoryName">
                      <div>
                        <span class="category-style">[{{scope.row.categoryName}}]</span>
                        <el-tag class="mar-l-10" size="mini" v-if="scope.row.skuFlag === 1" effect="light">多规格</el-tag>
                      </div>
                    </template>
                  </div>
                </div>
              </template>
            </el-table-column>

            <el-table-column width="100px" label="零售价格" prop="sellPrice" align="center">
              <template slot-scope="scope">
                ￥{{scope.row.sellPrice}}
              </template>
            </el-table-column>
            <el-table-column width="100px" label="库存" prop="stock" align="center">
              <template slot-scope="scope">
                {{scope.row.stock}}
              </template>
            </el-table-column>
            <el-table-column width="120px" label="操作" align="center">
              <template slot-scope="scope">
                <el-button type="primary" size="medium" class="select-g-btn"
                  :class="scope.row.selectFlag == '1' ? 'actived' : ''" @click="selectGoods(scope.row)">
                  {{ scope.row.selectFlag == '1' ? '已选择' : '选择' }}
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- 列表分页 -->
        <div class="pagination">
          <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="searchListQuery.currentPage" :page-sizes="[10, 20, 50, 100]"
            :page-size="searchListQuery.size" layout="total, sizes, prev, pager, next, jumper" :total="total">
          </el-pagination>
        </div>
        <div class="height-10"></div>
        <div style="text-align: center;">
          <el-button @click="dialogFormVisible = false">关闭</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import goodsDefaultOne from '@/assets/images/goods-1.png'
  import goodsDefaultTwo from '@/assets/images/goods-2.png'
  import {
    pagingPromotionGoods,
    checkPromotionGoods
  } from '@/api/sell/promotion'
  import {
    getDictByGroupName
  } from '@/api/common/common'
  import {
    listGoodsCategory
  } from '@/api/goods/goods'
  import {
    getGoodsTagListByBusType
  } from '@/api/goods/goodsTag'
  export default {
    data() {
      return {
        formActive: {
          showType: '1',
          goodsType: '0'
        },
        dataList: [],
        categoryData: [],
        categoryIds: [],
        listLoading: true,
        dialogFormVisible: false,
        total: null,
        searchLabelType: '',
        searchListQuery: {
          keyword: '',
          labelType: '',
          threeCategoryId: '',
          enterpriseId: this.getEnterpriseId(),
          currentPage: 1,
          size: 10,
          goodsTagId: ''
        },
        keyword: '',
        labelType: '',
        dict: {},
        goodsDefaultOne: goodsDefaultOne,
        goodsDefaultTwo: goodsDefaultTwo,
        selectLoading: true,
        selectList: [],
        dialogSkuVisible: false,
        skuLoading: true,
        visiblePopPrice: false,
        skuParamSettingValue: '',
        goodsTagId: '',
        goodsTagList: []
      }
    },
    // 初始化页面
    created() {
      console.log('item-add')
      this.listGoodsCategory()
      this.listGoodsTagList()
      this.initData()
      this.initDict()
    },
    mounted() {},
    filters: {},
    methods: {
      initData() {
        // 选择商品处理开始
        this.searchListQuery['oneCategoryId'] = ''
        this.searchListQuery['twoCategoryId'] = ''
        this.searchListQuery['threeCategoryId'] = ''
        const categoryIds = this.categoryIds
        if (categoryIds.length === 1) {
          this.searchListQuery['oneCategoryId'] = categoryIds[0]
        }
        if (categoryIds.length === 2) {
          this.searchListQuery['twoCategoryId'] = categoryIds[1]
        }
        if (categoryIds.length === 3) {
          this.searchListQuery['threeCategoryId'] = categoryIds[2]
        }
        this.listLoading = true
        pagingPromotionGoods(this.searchListQuery).then(response => {
          this.listLoading = false
          this.total = response.total
          this.dataList = response.records
          this.listLoading = false
          this.isSelectDataList()
        })
      },
      initDict() {
        getDictByGroupName('ProjectGoodsDTO').then(response => {
          this.dict = response.data
        })
      },
      // 获取商品标签
      listGoodsTagList() {
        const busType = 1
        getGoodsTagListByBusType(busType, this.getEnterpriseId()).then(response => {
          if (response.isError) return
          var data = response.data
          if (!data) {
            data = []
          }
          const defaultData = {
            goodsTagId: '',
            goodsTagName: '全部商品标签'
          }
          data.unshift(defaultData)
          this.goodsTagList = data
        })
      },
      // 获取类目
      listGoodsCategory() {
        const enterpriseId = this.getEnterpriseId()
        listGoodsCategory(enterpriseId).then(response => {
          this.categoryData = response.data
        })
      },
      handleSearch() {
        this.searchListQuery.currentPage = 1
        this.searchListQuery.goodsTagId = this.goodsTagId
        this.searchListQuery.keyword = this.keyword
        this.initData()
      },
      cleanSearch() {
        this.categoryIds = []
        this.keyword = ''
        this.labelType = ''
        this.goodsTagId = ''
        this.searchListQuery.keyword = ''
        this.searchListQuery.labelType = ''
        this.searchListQuery.threeCategoryId = ''
        this.searchListQuery.goodsTagId = ''
        this.initData()
      },
      isSelectDataList() {
        const dataList = this.dataList
        const arr = this.$parent.$refs.promotionItemList.dataList
        const map = new Map()
        arr.forEach(obj => {
          const goodsId = obj.goodsId
          map.set(goodsId, obj)
        })
        dataList.forEach(obj => {
          const goodsId = obj.goodsId
          const goods = map.get(goodsId)
          if (goods == null) {
            obj.selectFlag = '0'
          } else {
            obj.selectFlag = '1'
          }
        })
        this.dataList = dataList
      },
      selectGoods(item) {
        const arr = this.$parent.$refs.promotionItemList.dataList
        const goodsId = item.goodsId
        // 添加商品
        if (item.selectFlag === '0') {
          const startTime = this.$parent.startTime
          const endTime = this.$parent.endTime
          if (startTime !== undefined && startTime !== '' && endTime !== undefined && endTime !== '') {
            const data = {}
            const checkPromotionItemList = []
            checkPromotionItemList.push(item)
            data.promotionGoodsList = checkPromotionItemList
            data.activityType = this.$parent.activityType
            data.promotionId = this.$parent.promotionId
            data.startTime = startTime
            data.endTime = endTime
            const that = this
            checkPromotionGoods(data).then(
              response => {
                if (response.isError) return
                if (response.code === 501 || response.code === 502 ||
                  response.code === 503 || response.code === 504) {
                  this.msgError(response.msg)
                  let errorMsg = ''
                  if (response.code === 501) {
                    errorMsg = '已参加相同时段的秒杀活动'
                  }
                  if (response.code === 502) {
                    errorMsg = '已参加相同时段的社区团购活动'
                  }
                  if (response.code === 503) {
                    errorMsg = '商品不存在'
                  }
                  if (response.code === 504) {
                    errorMsg = '商品已下架'
                  }
                  if (response.data != null) {
                    if (that.dataList !== undefined && that.dataList.length > 0) {
                      for (let i = 0; i < that.dataList.length; i++) {
                        const isError = response.data.some(function(value) {
                          return value === that.dataList[i].goodsId
                        })
                        if (isError) {
                          that.dataList[i].errorMsg = errorMsg
                          that.$set(that.dataList, i, that.dataList[i])
                        }
                      }
                    }
                  }
                  return
                }
                item.errorMsg = undefined
                arr.push(item)
                const res = new Map()
                const arrRet = arr.filter((a) => !res.has(a.goodsId) && res.set(a.goodsId, 1))
                this.$parent.$refs.promotionItemList.updateData(arrRet)
                this.initData()
              })
          } else {
            arr.push(item)
            const res = new Map()
            const arrRet = arr.filter((a) => !res.has(a.goodsId) && res.set(a.goodsId, 1))
            this.$parent.$refs.promotionItemList.updateData(arrRet)
            this.initData()
          }
        } else {
          // 删除
          arr.splice(arr.findIndex(item => item.goodsId === goodsId), 1)
          const res = new Map()
          const arrRet = arr.filter((a) => !res.has(a.goodsId) && res.set(a.goodsId, 1))
          this.$parent.$refs.promotionItemList.updateData(arrRet)
          this.initData()
        }
      },
      // 更改当前页数
      handleCurrentChange(val) {
        this.searchListQuery.currentPage = val
        this.initData()
      },
      // 更改当前页面大小
      handleSizeChange(val) {
        this.searchListQuery.size = val
        this.initData()
      }
    }
  }
</script>
<style lang="less" scoped>
  // 页面总体布局
  .active-main {
    background: #f8f8f8;

    &:after {
      content: '';
      display: block;
      clear: both;
      font-size: 0;
    }

    .active-l {
      .main-content {
        padding-right: 4px;
        padding-left: 2px;
        height: 570px;
        overflow-x: hidden;
        overflow-y: auto;

        &::-webkit-scrollbar {
          width: 4px;
        }

        &::-webkit-scrollbar-thumb {
          border-radius: 10px;
          box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
          -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
          background: rgba(0, 0, 0, 0.2);
        }

        &::-webkit-scrollbar-track {
          box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
          -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
          border-radius: 0;
          background: rgba(0, 0, 0, 0.1);
        }

        h2 {
          margin: 0;
          font-size: 18px;
        }

        ul {
          padding: 0;
          margin: 0;

          &:after {
            content: '';
            display: block;
            clear: both;
            font-size: 0;
          }

          &.show-type-1 {
            li {
              .gooods-pic {
                img {
                  width: 100%;
                  height: 149px;
                  border-top-left-radius: 4px;
                  border-top-right-radius: 4px;
                }
              }
            }
          }

          &.show-type-2 {
            li {
              width: 48%;
              float: left;

              &:nth-child(odd) {
                margin-right: 4%;
              }

              .gooods-pic {
                img {
                  width: 100%;
                  height: 133px;
                  border-top-left-radius: 4px;
                  border-top-right-radius: 4px;
                }
              }

              .buy-now-type {
                display: none;
              }

              .price {
                label {
                  display: none;
                }
              }
            }
          }

          &.show-type-3 {
            li {
              display: -webkit-box;
              display: -webkit-flex;
              display: flex;
              flex-flow: row;
              align-items: center;
              padding: 0 5px 0 8px;

              .pic-box {
                margin-right: 6px;

                .gooods-pic {
                  img {
                    width: 82px;
                    height: 82px;
                  }
                }
              }

              .detail-box {
                -webkit-box-flex: 1;
                -webkit-flex: 1;
                flex: 1;
              }

              .tag {
                span {
                  padding: 1px 5px !important;
                }

                label {
                  padding: 1px 5px !important;
                }
              }

              .price {
                label {
                  display: none;
                }
              }

              .stock {
                display: none;
              }
            }
          }

          &.show-type-4 {
            li {
              display: -webkit-box;
              display: -webkit-flex;
              display: flex;
              flex-flow: row;
              align-items: center;
              padding: 8px 5px 8px 8px;

              &:nth-child(even) {
                .pic-box {
                  &.even {
                    display: none;
                  }

                  &.odd {
                    display: block;
                  }
                }
              }

              &:nth-child(odd) {
                .pic-box {
                  &.even {
                    display: block;
                  }

                  &.odd {
                    display: none;
                  }
                }
              }

              .pic-box {
                margin-right: 6px;

                .gooods-pic {
                  img {
                    width: 122px;
                    height: 122px;
                  }
                }
              }

              .detail-box {
                -webkit-box-flex: 1;
                -webkit-flex: 1;
                flex: 1;
                padding: 0 6px !important;
              }

              .desc {
                margin-top: -6px;
              }

              .tag {
                margin-top: -1px;
                margin-bottom: 0px;

                span {
                  padding: 1px 5px !important;
                }

                label {
                  padding: 1px 5px !important;
                }
              }

              .price {
                .flex-item {
                  >label {
                    display: -webkit-box;
                    display: -webkit-flex;
                    display: flex;
                    margin-top: -8px;
                  }
                }
              }

              .stock {
                display: none;
              }

              .info-bar {
                .buy-now-type {
                  display: none !important;
                }
              }

              .last-item {
                display: block !important;
                margin-top: 5px;
              }
            }
          }

          li {
            list-style-type: none;
            border-radius: 4px;
            box-shadow: 0 0 3px rgba(0, 0, 0, 0.3);
            margin-bottom: 15px;

            &:last-child {
              margin-bottom: 0;
            }

            .pic-box {
              &.odd {
                display: none;
              }
            }

            .gooods-pic {
              img {
                display: block;
              }
            }

            .desc {
              height: 36px;
              line-height: 1.5;
              overflow: hidden;
              text-overflow: ellipsis;
              display: -webkit-box;
              -webkit-line-clamp: 2;
              -webkit-box-orient: vertical;
              word-break: break-word;
            }

            .last-item {
              display: none;
            }

            .info-bar {
              .tag {
                line-height: 1.3;

                span {
                  background: #fed807;
                  color: #333;
                  padding: 2px 5px;
                }

                label {
                  background: #272727;
                  color: #fff;
                  padding: 2px 5px;
                  min-width: 60px;
                  box-sizing: border-box;

                  i {
                    color: #ffc81b;
                    font-style: normal;
                  }
                }
              }

              .price {
                span {
                  color: #FF4949;
                }

                label {
                  text-decoration: line-through;
                }
              }

              .stock {
                color: #6e6e6e;
              }

              label {
                font-weight: normal;
              }
            }
          }
        }

        .picture-default {
          background: #fe8096;
          display: flex;
          justify-content: center;
          align-items: center;
        }
      }
    }

    .active-r {
      border: 1px solid #ddd;
      border-radius: 10px;
      background: #fff;
      padding: 20px;
      min-height: 609px;

      h2 {
        font-size: 18px;
        margin: 0;
      }

      .tips {
        color: #409eff;
      }

      .select-table {
        min-height: auto !important;
      }
    }
  }

  .category-style {
    color: #6290ff;
    font-size: 13px;
  }

  .title-line-2 {
    height: 40px;
    line-height: 1.4;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    word-break: break-word;
  }

  // 商品弹窗样式
  .goods-layer {
    h3 {
      margin: -10px 0 0 0;
      color: #303133;
      font-size: 18px;
      text-align: center;
    }

    .dialog-footer {
      position: absolute;
      left: 0;
      bottom: 20px;
      width: 100%;
    }

    .table-container {
      height: 500px;
      overflow-x: hidden;
      overflow-y: auto;
    }
  }

  // 左侧手机模型样式
  .diy-bg-main {
    .diy-phone {
      float: left;
      width: 340px;
      border: 1px solid #ddd;
      border-radius: 10px;
      background: #fff;
      padding: 10px;
      overflow: hidden;

      &.none-border {
        border: none;
        background: none;
        padding: 0px 10px;
        border-radius: 0;
      }
    }

    .diy-phone .phone-head {
      height: 44px;
      background: #fff;
      position: relative;
    }

    .diy-phone .phone-head:before {
      content: "";
      position: absolute;
      top: 15px;
      left: 112px;
      height: 8px;
      width: 8px;
      background: #ddd;
      border-radius: 8px;
    }

    .diy-phone .phone-head:after {
      content: "";
      position: absolute;
      top: 15px;
      left: 128px;
      height: 8px;
      width: 50px;
      background: #ddd;
      border-radius: 8px;
    }

    .diy-phone .phone-title {
      height: 17px;
      /*background: url(../../../../assets/images/wx-top-2.png) 0 0 no-repeat;*/
      background-size: 100% auto;
      padding: 0 50px;
      font-size: 15px;
      color: #333333;
      text-align: center;
      line-height: 68px;
      cursor: default;
      overflow: hidden;
      display: block;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
  }
</style>
